package com.tca.common.compress.impl;

import com.tca.common.core.bean.Result;
import com.tca.common.core.utils.ValidateUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * @author zhouan
 * @Date 2021/9/11
 */
@Slf4j
public class ZipAdapter implements ICompressAdapter {


    private static final String PATH_SEPERATOR = "/";

    @Override
    public boolean supports(String fileName) {
        if (ValidateUtils.isEmpty(fileName)) {
            return false;
        }
        return fileName.toLowerCase().endsWith("zip");
    }

    @Override
    public Result<String> uncompress(String fileName, String dir) {
        try {
            File file = new File(fileName);
            ZipFile zip = new ZipFile(file, Charset.forName("GBK"));
            File unzipDir = ValidateUtils.isEmpty(dir)?
                    new File(file.getParentFile().getAbsolutePath()):
                    new File(dir);
            if (!unzipDir.exists() || !unzipDir.isDirectory()) {
                unzipDir.mkdirs();
            }
            for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();){
                ZipEntry entry = entries.nextElement();
                if(entry.isDirectory()){
                    continue;
                }
                String zipEntryName = entry.getName();
                //解压
                String outPath = new File(unzipDir, zipEntryName).getAbsolutePath();
                File parentFile = new File(outPath).getParentFile();
                if (!parentFile.exists() || !parentFile.isDirectory()) {
                    parentFile.mkdirs();
                }

                InputStream in = zip.getInputStream(entry);
                FileOutputStream out = new FileOutputStream(new File(outPath));
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                in.close();
                out.close();
            }
            return Result.success(unzipDir.getAbsolutePath());
        } catch (Exception e) {
            log.error("解压失败", e);
            return Result.failure("解压失败");
        }
    }

    @Override
    public Result<String> uncompress(String fileName) {
        return uncompress(fileName, null);
    }
}
